package com.googlecode.continuity.sample.basic.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.googlecode.continuity.core.client.AdminPage;
import com.googlecode.continuity.core.client.CoreGWT;
import com.googlecode.continuity.core.client.rpc.GroupRPCAsync;
import com.googlecode.continuity.core.client.rpc.UserRPCAsync;

/**
 * AdminStatistics
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public class AdminStatistics implements EntryPoint {
  private final String STRING_LOADING = "...";
  private final String STRING_ERROR_LOADING = "an error occured while contacting the server";
  private FlexTable list;
  private HorizontalPanel leftAlign;

  public void onModuleLoad() {
    leftAlign = new HorizontalPanel();
    list = new FlexTable();
    HTML spacer = new HTML("&nbsp;");
    spacer.setWidth("100%");
    leftAlign.add(list);
    leftAlign.add(spacer);

    list.setText(0, 0, "Number of registered users:");
    list.setText(0, 1, STRING_LOADING);
    //list.setWidget(0, 2, spacer);

    list.setText(1, 0, "Number of groups:");
    list.setText(1, 1, STRING_LOADING);

    AdminPage.getAdminPanel().add(leftAlign, "Statistics");
    AdminPage.getAdminPanel().selectTab(AdminPage.getAdminPanel().getWidgetIndex(leftAlign));

    refreshValues();
  }

  public void refreshValues() {
    list.setText(0, 1, STRING_LOADING);
    list.setText(1, 1, STRING_LOADING);
    ((UserRPCAsync) CoreGWT.getRPC("UserRPCAsync")).getUserCount(new AsyncCallback() {
      public void onFailure(Throwable throwable) {
        list.setText(0, 1, STRING_ERROR_LOADING);
      }

      public void onSuccess(Object object) {
        list.setText(0, 1, object.toString());
      }
    });

    ((GroupRPCAsync) CoreGWT.getRPC("GroupRPCAsync")).getGroupCount(new AsyncCallback() {
      public void onFailure(Throwable throwable) {
        list.setText(1, 1, STRING_ERROR_LOADING);
      }

      public void onSuccess(Object object) {
        list.setText(1, 1, object.toString());
      }
    });
  }
}
